//
//  EditSystemInfoViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 28/12/2022.
//

import UIKit
import RxSwift
import RxCocoa

class EditSystemInfoViewController: BaseViewController {
    private lazy var disposeBag = DisposeBag()
    var refreshDetailClosure: (()->Void)?
    var customView = EditSystemInfoView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        let panelsList = JobDetailModelHelper.shared.jobDetailModel.system_detail.panels.clone()
        let invertersList = JobDetailModelHelper.shared.jobDetailModel.system_detail.inverters.clone()
        let batteriesList = JobDetailModelHelper.shared.jobDetailModel.system_detail.batteries.clone()
        self.customView.setData(isBattery: JobDetailModelHelper.shared.jobDetailModel.system_detail.is_battery, panels: panelsList, inverters: invertersList, batteries: batteriesList)
    }
    func initUI(){
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.editSystemInformation())
        //MARK: - save 事件
        self.customView.saveBtn.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.customView.endEditing(true)
            strongSelf.toSaveSystemInfo()
        }.disposed(by: self.disposeBag)
    }
    private func toSaveSystemInfo(){
        let spvCheck = InstallationDetailVCHelper.shared.checkIfHaveOnlyOneBandForSPV(self.customView.combineView.panelTableView.list)//只有一个brand才传递true，有后台处理是否开启spv
        if JobDetailModelHelper.shared.jobDetailModel.job_status == PVDJobStatusValue.scheduled.rawValue{//start job前才做校验
            //如果新的panels的数据，在老的里边找不到就要检查是否开启spv
            //1)原来没数据，全部是新增的；2）原来有数据，删除又新增
            let firstIndex = self.customView.combineView.panelTableView.list.firstIndex(where: {
                let brandID = $0.panel_brand_id
                for tempModel in JobDetailModelHelper.shared.jobDetailModel.system_detail.panels{
                    if tempModel.panel_brand_id == brandID{
                        return true
                    }
                }
                return false
            })
            //新增数据，在老的数据中找不到
            if firstIndex == nil {
                //先校验spv check ，确认是否开启spv
                InstallationDetailVCHelper.shared.validSPVCheckBeforeNextOperation(panels: self.customView.combineView.panelTableView.list, companyID: JobDetailModelHelper.shared.jobDetailModel.company_id) { [weak self] spvCheckFlag in
                    guard let strongSelf = self else { return  }
                    if spvCheckFlag {
                        strongSelf.showValidSPVCheckView()
                    }else{
                        strongSelf.saveSystemInfo(spvCheck: spvCheck)
                    }
                }
            }else{//新增在老的中已经存在
                self.saveSystemInfo(spvCheck: spvCheck)
            }
        }else{//stard job后的处理，直接保存
            self.saveSystemInfo(spvCheck: spvCheck)
        }
    }
    //MARK: - 显示Valid SPV Check
    private func showValidSPVCheckView(){
        let view = CreateJobValidSPVCheckView()
        view.closure = { [weak self] spvCheck in
            self?.saveSystemInfo(spvCheck: spvCheck)
        }
        self.view.addSubview(view)
        view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    //MARK: - save system info
    private func saveSystemInfo(spvCheck: Bool){
        let vm = EditJobInfoService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideUpdatingView()
            if let data = result as? PVDDetailModel{
                JobDetailModelHelper.shared.jobDetailModel.spv_check = data.spv_check
                JobDetailModelHelper.shared.jobDetailModel.system_detail = data.system_detail
            }
            strongSelf.refreshDetailClosure?()//panel或inverter更新后，要刷新detail中底部按钮barcode计划数量
            strongSelf.navigationController?.popViewController(animated: true)
            
        } errorBlock: { (code, error) in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error)
        }
        ModelViewUtil.shared.showLoadingView(R.string.localizable.updating())
        let panesList =  self.customView.combineView.panelTableView.list + self.customView.combineView.panelTableView.delList
        let inverterList =  self.customView.combineView.inverterTableView.list + self.customView.combineView.inverterTableView.delList
        let batteryList =  self.customView.combineView.batteryCommonView.list + self.customView.combineView.batteryCommonView.delList
        vm.updateSystemInfo(panelList: panesList,inverterList: inverterList, batteryList: batteryList, haveBattery: self.customView.combineView.batteryCommonView.isBattery.value,spvCheck: spvCheck)
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
